const Controller = require('egg').Controller
const crypto = require('crypto')

class UserController extends Controller {
  // 测试
  test() {
    this.ctx.body = this.ctx.returnStatus.SUCCESS('测试成功！')
  }
  // 注册
  async register() {
    const { nickname, email, password, role } = this.ctx.request.body
    // 判断是否用户存在
    const checkRes = await this.service.user.getInfo({ email })
    if (checkRes) {
      this.ctx.body = this.ctx.returnStatus.USEREXIT()
    } else {
      // 加密密码
      const signature = crypto.createHash('md5').update(password).digest('hex')
      let res = await this.service.user.register({
        nickname,
        email,
        password: signature,
        role
      })
      this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
    }
  }
  // 登录
  async login() {
    const { email, password, role = 0 } = this.ctx.request.body
    // 判断为空
    const signature = crypto.createHash('md5').update(password).digest('hex')
    const res = await this.ctx.service.user.checkPwd({
      email,
      password: signature,
      role
    })
    console.log('登录结果', res)
    if (res) {
      this.ctx.session.user = res
      this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
    } else {
      this.ctx.body = this.ctx.returnStatus.PASSWORK('用户名或密码错误')
    }
  }
  // 获取登录用户信息
  async getInfo() {
    let res = this.ctx.session.user
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
  // 登出
  async logout() {
    this.ctx.user = null
    this.ctx.session = null
    this.ctx.body = this.ctx.returnStatus.SUCCESS()
  }
  // 充值
  async addBalance() {
    const { pay_value } = this.ctx.request.body
    // 判断为空
    const res = await this.ctx.service.user.addBalance({
      pay_value,
      user_id: this.ctx.user.id
    })
    this.ctx.session.user.balance = res.balance
    this.ctx.body = this.ctx.returnStatus.SUCCESS()
  }
  // 收入
  async getIncome() {
    let res = await this.service.order.getIncome({
      user_id: this.ctx.user.id
    })
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
}

module.exports = UserController
